package com.hunttown.mes.common.utils;


import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Font;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by panzining on 2018/8/6.
 */
public class ExportExcelUtils {

    private static Font headFont;
    private static Font contentFont;
    private static final int DEFAULT_COLUMN_LENGTH = 13;

    public static HSSFWorkbook getSingleSheetHSSFWorkbook(String sheetName, List<String> heads, List<List<String>> values, HSSFWorkbook wb) {

        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        /*
        try{
            sheetName = URLEncoder.encode(sheetName,"UTF-8");
            sheetName = excelSheetNameCheck(sheetName);
        } catch(Exception ex){
            sheetName = "illegal name";
        }*/

        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle titleStyle = wb.createCellStyle();
        HSSFCellStyle contentStyle = wb.createCellStyle();
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        headFont = wb.createFont();
        initHeadFont();
        titleStyle.setFont(headFont);

        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        contentFont = wb.createFont();
        initContentFont();
        contentStyle.setFont(contentFont);

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        int indexOfCell = 0;
        int length = heads.size();
        int chineseLength;
        int[] columnLength = new int[length];
        for (String item : heads) {
            cell = row.createCell(indexOfCell);
            cell.setCellValue(item);
            cell.setCellStyle(titleStyle);
            //初始化单元格长度
            chineseLength = getChineseLength(item);
            columnLength[indexOfCell] = Math.max(chineseLength, DEFAULT_COLUMN_LENGTH);
            indexOfCell++;
        }

        //创建内容
        int indexOfRow = 0;

        if (length == 0) {
            length = values.get(0).size();
            columnLength = new int[length];
            for (int i = 0; i < length; i++) {
                columnLength[i] = DEFAULT_COLUMN_LENGTH;
            }
        }

        for (List<String> rowItem : values) {
            row = sheet.createRow(indexOfRow + 1);
            indexOfCell = 0;
            for (String columnItem : rowItem) {
                //将内容按顺序赋给对应的列对象
                cell = row.createCell(indexOfCell);
                cell.setCellValue(columnItem);
                if (heads.size() == 0 && indexOfCell == 0) {
                    cell.setCellStyle(titleStyle);
                } else {
                    cell.setCellStyle(contentStyle);
                }

                //调整单元格的长度
                chineseLength = getChineseLength(columnItem);
                if (chineseLength > columnLength[indexOfCell]) {
                    columnLength[indexOfCell] = chineseLength;
                }
                indexOfCell++;
                if (indexOfCell >= length || indexOfCell >= 256) {
                    break;
                }
            }
            indexOfRow++;
        }

        for (int i = 0; i < length; i++) {
            if (columnLength[i] > 120) {    // 设置单元格长度，最长为120
                columnLength[i] = 120;
            }

            sheet.setColumnWidth(i, columnLength[i] * 256);
        }

        return wb;
    }

    //发送响应流方法
    private static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            response.setContentType("application/ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));  //解决中文乱码问题
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public static void writeFile(HSSFWorkbook wb, HttpServletResponse response, String fileName) {
        try {
            setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void initHeadFont() {
        headFont.setFontName("微软雅黑");
        headFont.setFontHeightInPoints((short) 10);
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    }

    private static void initContentFont() {
        contentFont.setFontName("微软雅黑");
        contentFont.setFontHeightInPoints((short) 10);
    }

    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位
     *
     * @param validateStr 指定的字符串
     * @return 字符串的长度
     */
    private static int getChineseLength(String validateStr) {

        if (StringUtils.isBlank(validateStr)) {
            return 0;
        }

        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";

        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < validateStr.length(); i++) {
            /* 获取一个字符 */
            String temp = validateStr.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }

        return valueLength;
    }

}
